﻿// ===============================================================================
// XCI.NET 西安交通信息WinForm开发框架 2018 版权所有
// ===============================================================================
using System;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using XCI.Extensions;

namespace XCI.Annotations
{
    /// <summary>
    /// 最小值验证属性
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class MinAttribute : DataTypeAttribute
    {
        private readonly double _min;

        /// <summary>
        /// 
        /// </summary>
        public object Min { get { return _min; } }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="min"></param>
        public MinAttribute(int min) : base("min")
        {
            _min = min;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="min"></param>
        public MinAttribute(double min) : base("min")
        {
            _min = min;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public override string FormatErrorMessage(string name)
        {
            if (ErrorMessage == null && ErrorMessageResourceName == null)
            {
                ErrorMessage = "The field {0} must be greater than or equal to {1}";
            }

            return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, _min);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public override bool IsValid(object value)
        {
            if (value.IsEmpty()) return true;

            var isDouble = double.TryParse(Convert.ToString(value), out var valueAsDouble);

            return isDouble && valueAsDouble >= _min;
        }
    }
}
